const IO = require('socket.io')
const {
	UserInfoUpdate,
	UserInfo
} = require('../model/userModel')
const socketModel = require('../model/socketModel')

function emitAsync(socket, emitName, data, callback) {
	return new Promise((resolve, reject) => {
		if (!socket || !socket.emit) {
			reject('pls input socket');
		}
		socket.emit(emitName, data, (...args) => {
			let response;
			if (typeof callback === 'function') {
				response = callback(...args);
			}
			resolve(response);
		});
	});
}


function creatSocket(app) {
	const io = IO(app, {
		pingInterval: 10000,
		pingTimeout: 5000,
		cookie: false,
		cors: true
	});
	// 每个客户端socket连接时都会触发 connection 事件
	io.on("connection", async (clientSocket) => {
		const user_socketid = clientSocket.id
		let user_id
		console.log('连接id=>', user_socketid, '连接时间=>', new Date().toLocaleString());
		// 触发客户端初始化事件
		await emitAsync(clientSocket, 'initSocket', clientSocket.id, async (userId) => {
			user_id = userId
			// 将id存入数据库
			UserInfoUpdate(user_id, {
				user_socketid: user_socketid
			})
			UserInfo(user_id).then(res=>{
				[user_info] = res
			})
			console.log('初始化连接=>', '初始化时间=>', new Date().toLocaleString());
		})
		// 获取当前用户信息
		// const [user_info] = 
		// 初始化成功并获取 获取好友列表及消息
		clientSocket.on('initSocketSuccess', async (userId, fn) => {
			console.log('初始化成功=>', '成功时间=>', new Date().toLocaleString());
			try {
				const [allMessage, friendList,addFriendsList] = await Promise.all([
					socketModel.UserOffLineMsg(user_id),
					socketModel.UserFriendList({user_id}),
					socketModel.UserFriendAddOffLineMsg(user_id)
				]);
				console.log(allMessage, friendList,addFriendsList)
				// 返回好友列表及离线信息
				fn(allMessage, friendList, addFriendsList)
				socketModel.UserDeleteOffLineMsg(user_id)
				socketModel.UserFriendAddOffLineDelete(user_id)
			} catch (err) {
				console.log(err);
			}
		})

		clientSocket.on('sendPrivateMsg', async (data, fn) => {
			try {
				if (!data) return;
				data.time = new Date().toLocaleString()
				await Promise.all([
					socketModel.UserSaveMsg(data),
					socketModel.getUserSocketId(data.to_user).then(arr => {
						let targetSocketId = arr[0].user_socketid
						if (io.sockets.connected[targetSocketId]) {
							console.log('推送成功');
							io.sockets.connected[targetSocketId].emit(
								'getPrivateMsg', data);
						} else {
							console.log('对方不在线 消息存入离线消息库');
							socketModel.UserSaveOffLineMsg(data)
						}
					}),
				]);
				console.log('sendPrivateMsg data=>', data, 'time=>', new Date()
					.toLocaleString());
				fn({
					success: true,
					message: '发送成功',
					data: data
				});
			} catch (error) {
				console.log('error', error.message);
				io.to(user_socketid).emit('error', {
					code: 500,
					message: error.message
				});
			}
		})

		//捕获客户端自定义信息

		// 添加为好友
		clientSocket.on('addFriends', async (data, fn) => {
			console.log('用户信息:' , user_info)
			let param = {
				from_user_id:user_info.user_id,
				to_user_id:data.user_id,
				remake:data.remake,
				to_user_icon:data.user_icon,
				from_user_icon:user_info.user_icon,
				from_user_sex:user_info.user_sex,
				from_user_nickname:user_info.user_nickname,
				isFriend:false
			}
			socketModel.getUserSocketId(data.user_id).then(arr => {
				const targetSocketId = arr[0].user_socketid
				if (io.sockets.connected[targetSocketId]) {
					// socketModel.UserFriendAddMsg(param)
					io.sockets.connected[targetSocketId].emit('addFriends', param);
				} else {
					console.log('对方不在线 消息存入离线好友申请消息库');
					socketModel.UserFriendAddMsg(param)
				}
				fn({
					success:true
				})
			})
		})

		// 同意添加好友
		clientSocket.on('agreeAddFriends', async (data, fn) => {
			let param = {
				user_id,
				friend_id: data.from_user_id,
				user_nickname: user_info.user_nickname,
				friend_nickname: data.from_user_nickname
			}
			const result = await socketModel.UserFriendAdd(param)
			
			// 添加成功后触发更新好友列表
			// 本人的好友列表
			const friendsList = await socketModel.UserFriendList({user_id})
			// 申请人的好友列表
			const applyFriendsList = await socketModel.UserFriendList({user_id:data.from_user_id})
			// 本人通过回调方法返回
			fn({
				success: true,
				message: '添加成功',
				friendsList
			})
			// 给申请方发送
			socketModel.getUserSocketId(data.from_user_id).then(arr => {
				const targetSocketId = arr[0].user_socketid
				if (io.sockets.connected[targetSocketId]) {
					io.sockets.connected[targetSocketId].emit('updataFriends', applyFriendsList);
				}
			})
		})

		//查询user
		clientSocket.on('findUser', async (id, fn) => {
			let result = await db.findUser(id)
			let isFriend = await db.isFriends({
				from_user: user_id,
				user_id: id
			})
			if (result) {
				let {
					user_name,
					user_head,
					user_id
				} = result
				fn([{
					user_name,
					user_head,
					user_id,
					isFriend
				}])
			} else {
				fn([])
			}
			console.log(123);
		})
		//监听客户端断开连接
		clientSocket.on('disconnect', async (msg) => {

		})


	});




	// const adminIo = io.of('/admin');
	// adminIo.on("connection", function(clientSocket) {
	//     console.log('连接adminIo的socket');
	//     console.log('当前socketID', clientSocket);
	//     // clientSocket.emit("receiveMsg", '连接adminIo的socket');
	// });

}

module.exports = creatSocket
